﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using FreeImageAPI;
using Image = System.Windows.Controls.Image;

namespace IV
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            string xxxx= this.Name;

            Grid grid = (Grid)this.FindName("grid");
            _box1 = (TextBox)grid.FindName("textbox1");
            _box2 = (TextBox)grid.FindName("textbox2");
            _imagecontainer = (Image)grid.FindName("ImageContainer");
            _slider = (Slider)grid.FindName("Slider");
            _slidervalue = (Label)grid.FindName("SliderValue");
            _box1.PreviewDragEnter += TextBox_DragEnter;
            _box1.PreviewDragOver += TextBox_DragOver;
            _box1.PreviewDrop += TextBox_Drop;
            _box1.PreviewDragLeave += TextBox_DragLeave;

            _box2.PreviewDragEnter += TextBox_DragEnter;
            _box2.PreviewDragOver += TextBox_DragOver;
            _box2.PreviewDrop += TextBox_Drop;
            _box2.PreviewDragLeave += TextBox_DragLeave;

        }

        private TextBox _box1;
        private TextBox _box2;
        private Image _imagecontainer;
        private Slider _slider;
        private Label _slidervalue;
        private string _indexfile;
        private string _colorfile;
        
        private FIBITMAP _output;

        private int _colorindex = 1;

        private void OnShow()
        {
            string indexfile = _box1.Text;
            string colorfile = _box2.Text;

            if (indexfile == _indexfile && colorfile == _colorfile)
            {
                return;
            }
            if (!File.Exists(indexfile) || !File.Exists(colorfile))
            {
                return;
            }

            try
            {
                FIBITMAP indexfib = FreeImage.LoadEx(indexfile);
                FIBITMAP colorfib = FreeImage.LoadEx(colorfile);

                FREE_IMAGE_COLOR_TYPE indexfict = FreeImage.GetColorType(indexfib);
                FREE_IMAGE_COLOR_TYPE colorfict = FreeImage.GetColorType(colorfib);


                uint indexbpp = FreeImage.GetBPP(indexfib);
                uint colorbpp = FreeImage.GetBPP(colorfib);

                if (indexbpp != 8 || colorbpp != 32)
                {
                    FreeImage.Unload(indexfib);
                    FreeImage.Unload(colorfib);
                    return;
                }

                unsafe
                {

                    uint width = FreeImage.GetWidth(indexfib);
                    uint height = FreeImage.GetHeight(indexfib);

                    uint colorwidth = FreeImage.GetWidth(colorfib);
                    uint colorheight = FreeImage.GetHeight(colorfib);

                    byte* indexpixel = (byte*) FreeImage.GetBits(indexfib);
                    byte* colorpixel = (byte*) FreeImage.GetBits(colorfib);

                    byte[] pixels = new byte[width * height * 4];

                    for (int h = 0; h < height; ++h)
                    {
                        for (int w = 0; w < width; ++w)
                        {
                            byte pixelindex = indexpixel[h * width + w];

                            pixels[h * width * 4 + w * 4 + 0] = colorpixel[(colorheight - _colorindex) * colorwidth * 4 + pixelindex * 4 + 2];
                            pixels[h * width * 4 + w * 4 + 1] = colorpixel[(colorheight - _colorindex) * colorwidth * 4 + pixelindex * 4 + 1];
                            pixels[h * width * 4 + w * 4 + 2] = colorpixel[(colorheight - _colorindex) * colorwidth * 4 + pixelindex * 4 + 0];
                            pixels[h * width * 4 + w * 4 + 3] = colorpixel[(colorheight - _colorindex) * colorwidth * 4 + pixelindex * 4 + 3];

                        }
                    }

                    if (!_output.IsNull)
                    {
                        FreeImage.Unload(_output);
                    }

                    _output = FreeImage.ConvertFromRawBits(pixels, (int) width, (int) height, (int) width * 4,32, 0, 0, 0, false);
                    Bitmap bmp = FreeImage.GetBitmap(_output);
                    _imagecontainer.Source = Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); ;
                    //                    FreeImageBitmap freeib = new FreeImageBitmap((int)width, (int)height, 32,0, pixels);
                    //                    _imagecontainer.Source = freeib;
                    //                    FreeImage.Save(FREE_IMAGE_FORMAT.FIF_TARGA, _output, "a.tga", FREE_IMAGE_SAVE_FLAGS.DEFAULT);
                    //                    FreeImage.Unload(_output);
                }

                FreeImage.Unload(indexfib);
                FreeImage.Unload(colorfib);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }






        }


        private void TextBox_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effects = DragDropEffects.Copy;
            }

            else
            {
                e.Effects = DragDropEffects.None;
            }
             

            e.Handled = true;
        }

        private void TextBox_DragLeave(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.None;
            e.Handled = true;
        }

        private void TextBox_Drop(object sender, DragEventArgs e)
        {
            string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (filenames != null && filenames.Length > 0)
            {
                TextBox box = (TextBox)sender;
                box.Text = filenames[0];
                

            }
        }


        private void TextBox_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effects = DragDropEffects.Copy;
            }
            else
            {
                e.Effects = DragDropEffects.None;
            }

            e.Handled = true;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {

        }

        private void textbox1_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            OnShow();
        }

        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            int newindex= (int)Math.Floor(e.NewValue);
            if (newindex != _colorindex)
            {
                _colorindex = newindex;
                _slidervalue.Content = newindex;
                OnShow();
            }

        }

        private void textbox2_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = (TextBox) sender;
            if (File.Exists(box.Text))
            {
                FIBITMAP colorfib = FreeImage.LoadEx(box.Text);
                uint colorheight = FreeImage.GetHeight(colorfib);

                _slider.Maximum = colorheight;
                _slider.Minimum = 1;

                if (colorheight > 1)
                {
                    _slider.TickFrequency = _slider.Width / (colorheight - 1);

                }
                _slider.Value = 1;
                _slidervalue.Content = "1";
                _colorindex = 1;

            }
           

        }
    }
}
